import express from "express";
import getTimeToData from "../common/getTimeToData.ts";

const singlePurchaseRanking = express.Router();

const detailData = async (params: any) => {
    // 如果没有传参默认本月数据
    if (params.length === 0 || Object.keys(params).length === 0) {
        const now = new Date();
        params = [new Date(now.getFullYear(), now.getMonth(), 1), now];
    }

    // 根据时间获取所有消费表的数据
    const res: any = await getTimeToData("consumptionRecord", params);

    const resStatistics = res
        .map((item) => {
            const { counterParty, tradeDescription, amount } = item;
            return {
                counterParty,
                tradeDescription,
                amount,
            };
        })
        .sort((a, b) => b.amount - a.amount);
    return resStatistics;
};

singlePurchaseRanking.post("/singlePurchaseRanking", async (req, res) => {
    try {
        const params = req.body;
        const dataRes: any = await detailData(params); // Wait for the query to complete
        res.send({
            code: 200,
            message: "单项消费金额排行 请求成功！",
            result: dataRes.slice(0,10),
        });
    } catch (error) {
        console.error("Error fetching file records:", error);
        res.status(500).send({
            code: 1,
            message: "单项消费金额排行 请求失败！",
            result: null,
        });
    }
});

export default singlePurchaseRanking;
